<?php
namespace app\controller;
use app\model\User as UserModel;
use think\facade\Db;

class DataModel
{
    public function index(){
        UserModer::select();
    }

    public function update(){
        $user = UserModel::find(302);
        $user->username = '吴文昊';
        $user->email = 'wuwenhao@163.com';
        //$user->force()->save();
        $user->allowField('username','email')->force()->save();

        //批量
//        $user = new UserModel();
//        $list = [
//            ['id'=>32,'username'=>'nihao','email'=>'xuwu@163.com'],
//            ['id'=>33,'username'=>'nihao','email'=>'xuwu@163.com'],
//            ['id'=>34,'username'=>'nihao','email'=>'xuwu@163.com'],
//        ];
//        $user->saveAll($list);

        //静态方法update。
//        UserModel::update([
//            'id'        =>  302,
//            'username'  =>  '徐林栋',
//            'email'     =>  'xulindong@163.com'
//        ]);

    }

    public function select(){
        //$id =302;
        $user = UserModel::select(302);
        return json($user);

        //只需要某个字段的值
//        $user = UserModel::where('id',302)->value('username');
//        return json($user);

//         $user = UserModel::whereIn('id',[302,301])->column('username','id');
//         return json($user);
        //输出单挑数据
//        return json(UserModel::getByUsername('蜡笔小新'));
    }

    public function field(){
        //UserModel::select();
        //Db::name('user')->select();

        $user = new  UserModel();
        echo $user->getUsername();
    }

    public function getAttr(){
        //动态获取器，如下更改email为大写。
        $user = UserModel::withAttr('email',function ($value){
            return strtoupper($value);
        })->find(302);
//        echo $user->status;
//        echo $user->nothing;
//        //该方法也可以获取源数据
//        echo $user->getData('status');
        return json($user);
        //return json($user->getData());
    }

    public function scope(){
        //$result = UserModel::scope('male')->select();
        $result = UserModel::price(80)->email('xiao')->select();
        return json($result);
    }

    public function softDelete(){
        //UserModel::destroy(302);
        //UserModel::find(302)->delete();
    }
}